<template>
  <view class="flex flex-column oh" style="max-height: 100vh;">
    <u-navbar
        :background="{ backgroundColor:'#9CE0FF'}"
        :border-bottom="false"
        title="巡检详情"
        title-color="#000"
        title-size="37"
    />
    <view class="">
      <view id="container" :style="{minHeight:`calc(100vh - ${top+80}px)`,maxHeight:`calc(100vh - ${top+80}px)`}" class="flex flex-column justify-between oys">
        <view class="mt-20">
          <sub-title title="巡检概况"></sub-title>
          <view class="flex space-evenly p-tb-20 pl-20">
            <view class="flex1 flex flex-column align-center justify-center color-fff bg-FF9900 h-200 mr-20 br-10">
              <text class="fz-40 lh-56 mb-10">{{ showData(unDone) }}</text>
              <text class="fz-24 lh-33">未巡检</text>
            </view>
            <view class="flex1 flex flex-column align-center justify-center color-fff bg-19BE6B h-200 mr-20 br-10">
              <text class="fz-40 lh-56 mb-10">{{ showData(done) }}</text>
              <text class="fz-24 lh-33">已巡检</text>
            </view>
            <view  class="flex1 flex flex-column align-center justify-center color-fff bg-FF6262 h-200 mr-20 br-10">
              <text class="fz-40 lh-56 mb-10">{{ showData(abnormal) }}</text>
              <text class="fz-24 lh-33">异常</text>
            </view>
          </view>
          <view class="p-lr-40">
            <view class="color-888888 fz-30 lh-42 w-full mb-20">
              <text>巡检开始时间</text>
              <text class="f-r">{{ workOrderInfo.startTime || '-' }}</text>
            </view>
            <view class="color-888888 fz-30 lh-42 w-full mb-20">
              <text>巡检结束时间</text>
              <text class="f-r">{{ workOrderInfo.endTime || '-'}}</text>
            </view>
            <view class="color-888888 fz-30 lh-42 w-full mb-20 flex">
              <text class="w-200">巡检人员</text>
              <view class="flex1 text-right">
                <text>{{ workOrderInfo.inspectionUser || '-' }}</text>
              </view>
            </view>
            <view class="color-888888 fz-30 lh-42 w-full mb-20 flex align-center justify-between" v-if="workOrderInfo.status == 5">
              <text>签名情况</text>
              <view class="flex align-center" @tap="signDetail">
                <image class="h-26 w-35 mr-10" src="@/static/images/equipment/eyeV2.png"></image>
                <text class="f-r color-19BE6B fz-30">已签名</text>
              </view>
            </view>
          </view>
          <sub-title title="巡检详情"></sub-title>
          <view class="p-lr-20 pb-35">
            <u-collapse :accordion="false">
              <u-collapse-item  v-for="(roomListItem, roomListItemIndex) in roomList" :key="roomListItemIndex" >
                <view slot="title" class="flex justify-between align-center w-full fz-34 pl-20 pr-15 ">
                  <view class="flex justify-center bg-19BE6B br-32 min-w-200 max-w-460 p-lr-22 p-tb-8">
                    <view class="lh-48 color-fff font-bold text-ellipsis-2">
                      <text>{{ roomListItem.roomName }}</text>
                    </view>
                  </view>
                  <text class="f-r"
                      :class="[ !roomListItem.doneNum ? 'color-2D8CF0':roomListItem.isAllDone && !roomListItem.abnormalNum ?'color-19BE6B':'color-FF6262']"
                  >
                    {{showNum(roomListItem.doneNum ,roomListItem.totalNum)}}
                  </text>
                </view>
                <view>
                  <view class="border-top-CCCCCC pt-15">
                    <view
                      v-for="(equipmentListItem, equipmentListItemIndex) in roomListItem.equipmentList"
                      :key="equipmentListItemIndex"
                      @tap="toCheckItemDetail(equipmentListItem)"
                      class="bg-E9F8FF br-10 mb-20" >
                      <view class="flex justify-between p-10">
                        <view class="flex flex1 oh">
                          <view class="br-round h-18 w-18 bg-9CE0FF mr-10 mt-15"></view>
                          <text class="flex1 fz-32 lh-45 color-333333">{{equipmentListItem.deviceName}}</text>
                        </view>
                        <image  class="h-28 w-14 mt-8" src="@/static/images/common/toPath.png" ></image>
                      </view>
                      <view
                          v-for="(standardListItem, standardListIndex) in equipmentListItem.standardList"
                          :key="standardListIndex"
                          class="fz-26 p-lr-20 pb-20 flex justify-between align-center"
                      >
                        <text class="block flex1 mr-20">{{ standardListItem.name }}</text>
                        <view class="flex2 flex justify-end">
                          <view v-if="standardListItem.type === '1' " class="flex flex-wrap ">
                            <view class="resultArrayItem break-all">
                              <text
                                  v-for="(resultArrayItem, resultArrayIndex) in standardListItem.resultArray"
                                  :key="resultArrayIndex"
                                  :class="[standardListItem.normal.split(',').includes(resultArrayItem) ?'color-19BE6B':'color-FF6262']"
                              >
                                {{resultArrayItem}}
                              </text>
                              <text class="color-FF6262" v-if="!standardListItem.resultArray">-</text>
                            </view>
                          </view>
                          <text  v-else :class="[standardListItem.status === '0' ?'color-19BE6B':'color-FF6262']" >
                            {{standardListItemValue(standardListItem)}}
                          </text>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </u-collapse-item>
            </u-collapse>
          </view>
        </view>
      </view>

    <view class="flex align-center justify-center h-150 border-top-EEEEEE sticky bottom0 bg-fff" v-if="allowOperation">
      <view v-if="isAssign" class="h-80 w-250 br-10 bg-19BE6B color-fff fz-30 lh-80 text-center" @tap="assign">
        <text>{{ assignTitle }}</text>
      </view>
      <view v-else class="h-80 w-250 br-10 border-19BE6B color-19BE6B fz-30 lh-80 text-center" @tap="isTimePickerShow = true">
        <text>延长工单</text>
      </view>
    </view>

  </view>

    <u-picker
      :defaultTime="defaultTime"
      v-model="isTimePickerShow"
      :params="params"
      mode="time"
      safe-area-inset-bottom
      @confirm="confirmDelay"
      control
    >
    </u-picker>
  </view>
</template>

<script>
import SubTitle from "@/components/SubTitle/SubTitle";
import getNavBarHeight from "@/mixins/getNavBarHeight";
import {workOrderInfo, querySign ,delayEndDate} from "@/api/inspection/task";
import {listWorkOrderDevice} from "@/api/inspection/planDevice";
import dayjs from '@/libs/dayjs.min.js'
import { INSPECTION_ORDER_STATUS } from '@/utils/dict'


export default {
  name: "allOrderDetail",
  components: {SubTitle},
  mixins: [getNavBarHeight],
  onLoad(options) {
    this.workOrderId = options.workOrderId
  },
  onShow(){
    this.doQuery()
  },
  created() {
    this.isNurse = this.$auth.hasRoleOr(['head-nurse','nurse'])
    this.isManagerOrAdmin = this.$auth.hasRoleOr(['manager','admin','co-admin'])
    this.isEngineer = this.$auth.hasRole('engineer')
  },
  data() {
    return {
      workOrderInfo: {},
      workOrderId: '',
      unDone: 0,
      done: 0,
      abnormal: 0,
      roomList: [],
      isNurse: false,
      isManagerOrAdmin: false,
      isEngineer: false,
      //设备原始列表
      deviceListoriginalData: [],
      defaultTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      isTimePickerShow: false,
      params: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false
      },
    }
  },
  computed:{
    allowAssignOrder(){
      return [INSPECTION_ORDER_STATUS.UNDISTRIBUTED,INSPECTION_ORDER_STATUS.WILL,INSPECTION_ORDER_STATUS.DOING]
    },
    allowDelayOrder(){
      return [INSPECTION_ORDER_STATUS.OVERTIME,INSPECTION_ORDER_STATUS.TIMEOUT]
    },
    isAssign(){
      return this.allowAssignOrder.find(el=>el.value === this.workOrderInfo.status)
    },
    allowOperation(){
      return this.isAssign || this.allowDelayOrder.find(el=>el.value === this.workOrderInfo.status)
    },
    assignTitle(){
      if(this.workOrderInfo.status===INSPECTION_ORDER_STATUS.UNDISTRIBUTED.value){
        return '派单'
      }else if(this.workOrderInfo.status===INSPECTION_ORDER_STATUS.WILL.value){
        return '转派'
      }
      return '转派'
    }
  },

  watch: {
    deviceListoriginalData(newValue) {
      if(!newValue) return
      //生成树结构
      this.roomList = newValue.reduce((pre, next) => {
        let temp = pre.find(item => {
          return item.roomId === next.roomId
        })
        if (temp) {
          temp.equipmentList.push(next)
        } else {
          pre.push({roomId: next.roomId, roomName: next.roomName, equipmentList: [next]})
        }
        return pre
      }, [])

      //计算每个房间的总标准数和已完成标准数
      this.roomList.forEach(roomListItem => {
        roomListItem.totalNum = roomListItem.equipmentList.reduce((pre,next) => {
          return pre + next.standardList.length
        },0)
        roomListItem.doneNum = roomListItem.equipmentList.reduce((pre,next) => {
          let temp = next.standardList.reduce((standardListPre,standardListnext) => {
            if(standardListnext.result || standardListnext.value ||  standardListnext.value== 0){
              standardListPre++
            }
            return standardListPre
          },0)
          return pre + temp
        },0)
        roomListItem.abnormalNum = roomListItem.equipmentList.reduce((pre,next) => {
          let temp = next.standardList.reduce((standardListPre,standardListnext) => {
            if(standardListnext.status === '1'){
              standardListPre++
            }
            return standardListPre
          },0)
          return pre + temp
        },0)
        roomListItem.isAllDone = roomListItem.totalNum === roomListItem.doneNum
      })
      this.done = 0
      this.unDone = 0
      this.abnormal = 0
      //统计未巡检.已巡检.异常数
      newValue.forEach(item => {
        item.standardList.forEach(standardListItem => {
          if(standardListItem.value || standardListItem.value == 0 || standardListItem.result ){
            this.done++
            if(standardListItem.status == 1){
              this.abnormal ++
            }
          }else{
            this.unDone ++
          }
        })
      })

    },
  },
  methods: {
    doQuery() {
      workOrderInfo(this.workOrderId).then(res => {
        this.workOrderInfo = res.data
      })
      listWorkOrderDevice({workOrderId: this.workOrderId}).then(res => {
        //房间、设备、标准根据Id升序排序
        // res.data.sort((pre, next) => {
        //   if (next.roomId === pre.roomId) {
        //     return pre.deviceId - next.deviceId;
        //   } else {
        //     return pre.roomId - next.roomId;
        //   }
        // })
        res.data.forEach(item => {
          // item.standardList.sort((pre, next) => {
          //   return pre.standardId - next.standardId
          // })
          item.standardList.forEach(standardListItem => {
            if(standardListItem.type === '1' && standardListItem.result){
              standardListItem.resultArray = standardListItem.result.split(',')
            }
          })
        })
        this.deviceListoriginalData = res.data
      })
    },
    assign(){
      const workOrderIdList = [this.workOrderInfo.workOrderId]
      const hospitalId = this.workOrderInfo.hospitalId
      const companyId = this.workOrderInfo.companyId
      this.$tab.navigateTo(`/pages/work/choose-worker?workOrderIdList=${workOrderIdList}&hospitalId=${hospitalId}&companyId=${companyId}&byBatch=1`)
    },
    //延长
    confirmDelay(e){
      const now = new Date()
      let endDate = `${e.year}-${e.month}-`
      if(now.getFullYear() === parseInt(e.year) && now.getMonth()+1 === parseInt(e.month) && now.getDate() > parseInt(e.day)){
        endDate += now.getDate()
      }else{
        endDate += e.day
      }
      delayEndDate({workOrderId:this.workOrderInfo.workOrderId, delayEndDate:endDate}).then(res => {
        if(res.code == 200){
          uni.showToast({
            title: '延长工单日期成功！',
            duration: 2000,
            icon:'none'
          });
          setTimeout(()=> {
            uni.navigateBack({
              delta: 1
            })
          },1900)
        }
      })
    },
    showData(data) {
      return data > 99 ? "99+" : data;
    },
    showNum(doneNum ,totalNum){
      if(!doneNum){
        return '待巡检'
      }
      return doneNum + '/' + totalNum
    },

    toCheckItemDetail(equipmentItemInfo) {
      this.$tab.navigateTo('/pages/work/check-item-detail?deviceId=' + equipmentItemInfo.deviceId + '&workOrderId=' + this.workOrderInfo.workOrderId + '&workOrderDeviceId=' +  equipmentItemInfo.workOrderDeviceId)
    },

    //获取巡检标准的值
    standardListItemValue(item) {
      if (item.type == 0 || item.type == 1) {
        return  item.result ? item.result : '-'
      }else{
        return  item.value || item.value==0 ? parseFloat(item.value) + (item.unit ? item.unit : '') : '-'
      }
    },
    //查看签名情况
    signDetail(){
      querySign(this.workOrderId).then(res => {
        uni.previewImage({
          urls: [res.data.url], //需要预览的图片链接列表
          indicator: "none", //图片指示器样式 "default" - 底部圆点指示器； "number" - 顶部数字指示器； "none" - 不显示指示器
        });
      })
    }
  },
}
</script>

<style lang="scss">
page {
  background-color: #fff;
}
</style>
<style lang="scss" scoped>
</style>
